package cn.example.practice.servlet;


import cn.example.practice.util.VerifyCodeGenerator;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.imageio.ImageIO;
import java.io.IOException;

/**
 * Servlet implementation class VerifyCodeImg
 */
@WebServlet(name = "VerifyCodeImgServlet", urlPatterns = "/verifyCodeImgServlet")
public class VerifyCodeImgServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 设置响应类型和缓存控制
            setResponseHeaders(response);

            // 生成验证码
            VerifyCodeGenerator generator = new VerifyCodeGenerator();

            // 保存验证码到session
            request.getSession().setAttribute("code", generator.getCode().toLowerCase());

            // 输出图片
            ImageIO.write(generator.getImage(), "JPEG", response.getOutputStream());
        } catch (IOException e) {
            // 记录错误并返回适当的错误响应
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "生成验证码时发生错误");
        }
    }

    private void setResponseHeaders(HttpServletResponse response) {
        response.setContentType("image/jpeg");
        response.setHeader("pragma", "no-cache");
        response.setHeader("cache-control", "no-cache");
        response.setHeader("expires", "0");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
